﻿using System;
using System.Collections.Specialized;
using Jbe.Composite.Extensions;
using Jbe.TestSuite.Infrastructure.Interface;
using Jbe.TestSuite.Message.Demo.Properties;
using Microsoft.Practices.Composite.Regions;
using Jbe.TestSuite.Infrastructure.Interface.Documents;

namespace Jbe.TestSuite.Message.Demo.Applications
{
    internal class ModuleController
    {
        private readonly IApplicationContainer container;
        private readonly IRegionManager regionManager;
        private readonly IUIElementCreationService uiElementCreationService;
        private DelegateCommand closeCommand;
        private DemoPresentationModel presentationModel;


        public ModuleController(IApplicationContainer container, IRegionManager regionManager, IUIElementCreationService uiElementCreationService)
        {
            this.container = container;
            this.regionManager = regionManager;
            this.uiElementCreationService = uiElementCreationService;
        }


        public void Initialize()
        {
            closeCommand = new DelegateCommand(Close);
            DocumentCommands.Close.RegisterCommand(closeCommand);

            IToolBarItem toolBarItem = uiElementCreationService.CreateToolBarItem(Resources.MessageDemo, Resources.MessageImage);
            toolBarItem.Click += MessageDemoToolBarItemClick;
            regionManager.Regions[ShellRegionNames.MainToolBar].Add(toolBarItem);
        }

        private void MessageDemoToolBarItemClick(object sender, EventArgs e)
        {
            if (presentationModel == null)
            {
                presentationModel = container.Resolve<DemoPresentationModel>();
                presentationModel.View.DataContext = presentationModel;
                regionManager.Regions[ShellRegionNames.ContentRegion].ActiveViews.CollectionChanged += ActiveViewsCollectionChanged;
                regionManager.Regions[ShellRegionNames.ContentRegion].Add(presentationModel.View);
            }
            regionManager.Regions[ShellRegionNames.ContentRegion].Activate(presentationModel.View);
        }

        private void ActiveViewsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.NewItems != null && e.NewItems.Contains(presentationModel.View)) { closeCommand.IsActive = true; }
            else if (e.OldItems != null && e.OldItems.Contains(presentationModel.View)) { closeCommand.IsActive = false; }
        }

        private void Close()
        {
            regionManager.Regions[ShellRegionNames.ContentRegion].Remove(presentationModel.View);
            regionManager.Regions[ShellRegionNames.ContentRegion].ActiveViews.CollectionChanged -= ActiveViewsCollectionChanged;
            presentationModel = null;
        }
    }
}
